<?php
namespace control;
/*
* 劳动报酬清单类
*/

class laborSalaryClass extends adIndexClass
{
    private const page = 'laborSalary';
    private const table = 'labor_salary';
    private const table_detail = 'labor_salary_detail';
    private const table_company = 'labor_company';
    private const title = '劳动报酬清单';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'      => [
                        'name'  => "单据编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'month' => [
                        'name'  => "月份",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'company'  => [
                        'name'  => "派遣单位",
                        'width' => 200,
                    ],
                    'laborAgreement'         => [
                        'name'  => '派遣协议编号',
                        'width' => 200,
                    ],
                    'totalPeople'          => [
                        'name'  => '清单人数',
                        'width' => 150,
                    ],
                    'stid'    => [
                        'name'  => '申请人',
                        'width' => 150,
                    ],
                    'money'    => [
                        'name'  => '劳务报酬金额合计（' . static::$unit . '）',
                        'width' => 200,
                    ],
                    'time'    => [
                        'name'  => '单据日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'    => [
                        'name'  => '状态',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "月份"     => text(array("name" => "month", 'laydate' => ['type' => 'month'])),
                    "派遣协议编号" => text(array("name" => "agreementNo")),
                ],
                [
                    '派遣单位'   => selectMultiple(["name" => "companyId", 'sqlId' => 'id', 'sqlField' => 'name', 'table' => 'labor_company', 'where' => "state = '启用' order by orderNo", 'class' => 'width200']),
                    "单据日期" => text(array("name" => "startTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "审批状态" => select(["name" => "state", 'option' => $this->stateOption]).
                    hidden(array("name"=>"id","value"=>$this->get('id')?:$this->post('id'))),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{})\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button, searchOption: "{id:'".$this->get('id')."'}"));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            'companyId' => $this->post('companyId'),
            "state" => $this->post('state'),//状态
        );
        $and = "";
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'));
        }
        if ($this->post('agreementNo')) {
            $and .= " and aid in (select id from labor_agreement where orderNo like '%" . $this->post('agreementNo') . "%')";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'month',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;

        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "company":
                        $company = query(self::table_company, "id = '$array[companyId]'");
                        $row[] = $company['name'];
                        break;
                    case "laborAgreement":
                        $laborAgreement = query('labor_agreement', "id = '$array[aid]'");
                        $row[] = $laborAgreement['orderNo'];
                        break;
                    case "totalPeople":
                        $totalPeople = static::total(array('table' => self::table_detail, "where" => "orderId = '$array[id]'"));
                        $row[] = $totalPeople;
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    case "money":
                        $money = find(array('table' => self::table_detail, 'where' => "orderId = '$array[id]'", 'sum' => "money"));
                        $row[] = $money;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . $this->js() . clear;
        return json_encode($json, 320);
    }


    public function js()
    {
        return <<<eof
<script>
function getOrderInfo(e){
    $.post(root+'control/adIndex.html?cla=laborSalary&fun=getOrderInfo',{id:e.value},function(res) {
        $("#orderNo").empty().append(res.html)
    },'json')
}
</script>
eof;

    }

    public function getOrderInfo()
    {
        $json['html'] = selectMultiple(["name" => "aid", 'title' => '请选择', 'sqlId' => 'id', 'sqlField' => 'orderNo', 'table' => 'labor_agreement', 'where' => "state = '已通过' and companyId = '" . $this->post('id') . "' order by orderNo", 'class' => 'text']);
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "月份：" => text(array('name' => 'month', 'laydate' => ['type' => 'month'], 'value' => date('Y-m'))),
            ),
            array(
                must . "派遣单位" => selectMultiple(["name" => "companyId", 'change' => 'getOrderInfo', 'title' => '请选择', 'sqlId' => 'id', 'sqlField' => 'name', 'table' => 'labor_company', 'where' => "state = '启用' order by orderNo", 'class' => 'text'])
            ),
            array(
                must . "协议编号" => "<span id='orderNo' style='width: 100%'>" . selectMultiple(["name" => "aid", 'title' => '请选择', 'sqlId' => 'id', 'sqlField' => 'orderNo', 'table' => 'labor_agreement', 'where' => "state = '已通过' and companyId = '' order by orderNo"]) . "</span>"
            )
        )));
        //返回
        return $this->layer(array("title" => "新增", "height" => 320, "width" => 800, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'month' => $this->post('month'),
            'companyId' => $this->post('companyId'),
            'aid' => $this->post('aid'),
        ];
        $annotation = [
            'month' => '月份',
            'companyId' => '派遣单位',
            'aid' => '协议编号',
        ];
        $rules = [
            'month' => 'required',
            'companyId' => 'required',
            'aid' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(array('table' => self::table, "where" => "month = '$field[month]' and companyId = '$field[companyId]' and aid = '$field[aid]' and id !='$id'")) > 0) {
            $json['warn'] = '已存在此月份的报酬清单';
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'LWBC' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $department = query('department', "id = '" . $this->controlJob['departmentId'] . "'");
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'deptName' => $department['name'],
                    'state' => '草稿',
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 审核按钮
     *
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => [
                    "act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'name' => '劳动报酬清单',
                        'table' => self::table,
                        'process' => [
                            // 预览函数
                            'detail' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'detail',
                            ],
                            //执行发起时验证函数
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        // 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => [
                    "act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state'],   //变更字段 可多个
                        'value' => [
                            'state' => ['草稿', '已通过'],
                        ],
                        // 审核时回调
                        'process' => [
                            //执行首次审核时验证
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //执行末次审核后处理
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'finish',
                                'data'=>['id'=>$info['id']]
                            ],
                        ],
                    ], 320)),
                ],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];

        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state'],   //变更字段 可多个
                        'value' => [
                            'state' => ['草稿'],
                        ],
                        'process' => [
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'cancelFun',
                                'data'=>['id'=>$info['id']]
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        return $button;
    }

    public function cancelFun($data){
        delete(array('table'=>'record','where'=>"sourceId = '$data[id]'"));
    }
    public function finish($data){
        $info = query(self::table, " id = '{$data['id']}'");
        $money = find(array('table'=>self::table_detail,'where'=>"orderId = '$info[id]'",'sum'=>"money"));
        $balance = find(array('table' => "record", 'where' => "typeId = '$info[companyId]'", 'sum' => "money"));
         insert(array(
           'table'=>'record',
           'field'=>[
               'type'=>'派遣单位',
               'typeId'=>$info['companyId'],
               'targetDate'=>date('Y-m-d',strtotime($info['time'])),
               'classify'=>'劳动报酬清单',
               'direction'=>'+',
               'money'=>$money,
               'balance'=>$balance+$money,
               'orderNo'=>$info['orderNo'],
               'sourceTable'=>self::table,
               'sourceId'=>$info['id'],
               'text'=>'劳动报酬清单【'.$info['orderNo'].'】',
               'stName'=>self::findStaff($info['stid']),
           ]
        ));
    }
    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "menu" => [
                    'detail' => '基本信息',
                    'peopleList' => '报酬清单',
                ],
            );

            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                $button[] = [
                    "name" => "上传附件",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "uploadFile",
                    "post" => ["id" => $info['id']],
                ];
            }
            if ($this->power(self::page, "del") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            //审核按钮
            $button = array_merge($this->auditButton($info),$button);
            $company = query(self::table_company, "id = '$info[companyId]'");
            $orderInfo = query('labor_agreement', "id = '$info[aid]'");
            $audit = query('audit', " targetId = '$info[id]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        "单据编号" => $info['orderNo'],
                        "月份" => $info['month'],
                        "派遣单位" => $company['name'],
                        "派遣协议编号" => $orderInfo['orderNo'],
                    ),
                    array(
                        "申请人部门" => $info['deptName'],
                        "申请人" => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                        "提交时间" => self::null($audit['commitTime']),
                    ),
                    array(
                        "状态" => $info['state'],
                    ),
                ),
                '附件' => array(
                    array(
                        fileUploadClass::showFile($info['id'], '劳动报酬清单')
                    )
                ),
                '流程' => array(
                    array(
                        auditClass::auditRecord(self::table, $info['id']),
                    ),
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    public function uploadFile(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    fileUploadClass::addFileComponent($this->post('id'), '劳动报酬清单', self::page, 'laborSalaryUploadFileForm')
                ),
            )
        ));
        //返回
        return $this->layer(array("title" => "上传附件", "height" => 300, "width" => 900, "html" => $html));
    }

    public function uploadFileEdit(): bool|string
    {
        $fileIdArr = $this->post('fileId') ?: [];
        $id = $this->post('id');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($id)) {
            $json['warn'] = '未找到ID';
        } else {
            $warn = update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
            if (in_array($warn, ['新增成功', '更新成功'])) {
                $json['warn'] = 2;
                $_SESSION['warn'] = '上传成功';
            } else {
                $json['warn'] = '上传失败';
            }
        }
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function peopleListOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "姓名" => text(array("name" => "name")),
                    "联系方式"   => text(array("name" => "tel")),
                    "身份证号"   => text(array("name" => "idCard")).
                        hidden(array('name' => 'id', 'value' => $this->get('id')))
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 派遣清单
     */
    public function peopleList(): bool|string
    {
        $html = $this->homeOptions(false);
        $info = query(self::table, "id = '" . $this->get('id') . "'");
        //控件
        $button = "";
        if ($this->power(self::page, 'edit')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."', fun:'peopleListSearch'})\">导入</span>";
        }
        if ($this->power(self::page, "edit")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'delMx'})\">删除</span>\n";
        }
        $money = find(array('table' => self::table_detail, 'where' => "orderId = '$info[id]'", 'sum' => 'money'));
        $button .= "<span style='margin-left: 20px;font-weight: bold;'>应发合计：{$money}</span>";
        $json['html'] = $this->searchExecute([
            'html'         => $html,
            'layout'       => 'pop',
            'toolButton'   => $button,
            'option'      => '{fixed:true,row:2}'
        ]);
        return json_encode($json, 320);
    }

    /**
     * 派遣清单
     * @return bool|string
     */
    public function peopleListSearch(): bool|string
    {
        $info = query(self::table, "id = '" . $this->post('id') . "'");
        //全等查询数组
        $equal = array(
        );
        $like = array(
            "name" => $this->post('staffName'),//员工
        );
        $and = " and orderId = '$info[id]'";
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and jobId in (select id from job where departmentId = '{$this->post('departmentId')}') ";
        }
        //获取查询结果
        $where = search(array("=" => $equal, "like" => $like)) . $and;
        $page = $this->page(array("table" => self::table_detail, "where" => $where, "order" => " list asc"));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        $_SESSION[self::page]['id'] = $info['id'];
        $tr = '';
        //获取记录
        foreach ($page['array'] as $array) {
            $tr .= <<<eof
                 <tr>
                     <td><label class="listCheckbox"><input name="listId[]" type="checkbox" value="$array[id]"><span></span></label></td>
                     <td>{$array['name']}</td>
                     <td>{$info['month']}</td>
                     <td>{$array['workDay']}</td>
                     <td>{$array['salaryDay']}</td>
                     <td>{$array['baseMoney']}</td>
                     <td>{$array['jobMoney']}</td>
                     <td>{$array['telFee']}</td>
                     <td>{$array['trafficFee']}</td>
                     <td>{$array['performance']}</td>
                     <td>{$array['workAgeFee']}</td>
                     <td>{$array['educationFee']}</td>
                     <td>{$array['jobTitleFee']}</td>
                     <td>{$array['temperatureFee']}</td>
                     <td>{$array['overtimeFee']}</td>
                     <td>{$array['otherFee']}</td>
                     <td>{$array['leaveMoney']}</td>
                     <td>{$array['lateMoney']}</td>
                     <td>{$array['otherDecMoney']}</td>
                     <td>{$array['money']}</td>
                     <td>{$array['text']}</td>
                     <td>{$array['idCard']}</td>
                     <td>{$array['tel']}</td>
                 </tr>
eof;
        }

        $html = <<<eof
<div class="table_many_shell">
<table id="subjectTable" class="tableMany">
    <thead>
        <tr>
            <td rowspan="2" style="vertical-align:middle"><label title="全选" class="listCheckbox"><input type="checkbox" form="listForm" name="listId" onchange="checkAll(this)"><span></span></label></td>
            <td rowspan="2" style="vertical-align:middle">姓名</td>
            <td rowspan="2" style="vertical-align:middle">月份</td>
            <td rowspan="2" style="vertical-align:middle">出勤天数</td>
            <td rowspan="2" style="vertical-align:middle">受薪天数</td>
            <td colspan="15" class="center">工结构明细</td>
            <td rowspan="2" style="vertical-align:middle" class="center">备注</td>
            <td rowspan="2" style="vertical-align:middle" class="center">身份证号</td>
            <td rowspan="2" style="vertical-align:middle" class="center">手机号</td>
        </tr>
        <tr>
            <td>基本工资</td><td>岗位工资</td>
            <td>通讯补贴</td><td>交通补贴</td>
            <td>绩效工资</td><td>工龄工资</td>
            <td>学历津贴</td><td>职称津贴</td>
            <td>高温补贴</td><td>加班补贴</td>
            <td>其他补贴</td><td>病事假扣款</td>
            <td>迟到早退</td><td>其他扣款</td>
            <td>应发工资</td>
        </tr>
    </thead>
    <tbody>
     {$tr}
    </tbody>
</table>
</div>
<style>
#subjectTable{margin-left: 0;}
</style>
eof;

        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form class='listForm' name='recordForm'>" . $html . "</form>" . $page['button'];
        return json_encode($json, 320);
    }


    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'姓名',
                    'aliasName'=>'姓名',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'身份证号',
                    'aliasName'=>'身份证号',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'手机号码',
                    'aliasName'=>'手机号码',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'出勤天数',
                    'aliasName'=>'出勤天数',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'受薪天数',
                    'aliasName'=>'受薪天数',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'基本工资',
                    'aliasName'=>'基本工资',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'岗位工资',
                    'aliasName'=>'岗位工资',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'通讯补贴',
                    'aliasName'=>'通讯补贴',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'交通补贴',
                    'aliasName'=>'交通补贴',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'绩效工资',
                    'aliasName'=>'绩效工资',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'工龄工资',
                    'aliasName'=>'工龄工资',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'学历津贴',
                    'aliasName'=>'学历津贴',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'职称津贴',
                    'aliasName'=>'职称津贴',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'高温补贴',
                    'aliasName'=>'高温补贴',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'加班补贴',
                    'aliasName'=>'加班补贴',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'其他补贴',
                    'aliasName'=>'其他补贴',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'病事假扣款',
                    'aliasName'=>'病事假扣款',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'迟到早退',
                    'aliasName'=>'迟到早退',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'其他扣款',
                    'aliasName'=>'其他扣款',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'应发工资',
                    'aliasName'=>'应发工资',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                    'isMust'=>false,
                ]
            ]
        };
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        }  else {
            $exampleData[] = [
                '张三', '500223199412011XXX', '13000000000', '22', '22', 3000, 2000, 100, 100, 0, 100, 0, 0, 0, 20, 0, 0, 0, 0, 5320, ''
            ];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '姓名'=>$example[0],
                            '身份证号'=>$example[1],
                            '手机号码'=>$example[2],
                            '出勤天数'=>$example[3],
                            '受薪天数'=>$example[4],
                            '基本工资'=>$example[5],
                            '岗位工资'=>$example[6],
                            '通讯补贴'=>$example[7],
                            '交通补贴'=>$example[8],
                            '绩效工资'=>$example[9],
                            '工龄工资'=>$example[10],
                            '学历津贴'=>$example[11],
                            '职称津贴'=>$example[12],
                            '高温补贴'=>$example[13],
                            '加班补贴'=>$example[14],
                            '其他补贴'=>$example[15],
                            '病事假扣款'=>$example[16],
                            '迟到早退'=>$example[17],
                            '其他扣款'=>$example[18],
                            '应发工资'=>$example[19],
                            '备注'=>$example[20],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
            $text   = $this->control['name'] . "下载了" . self::title . "导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入分析*/
    public function importData()
    {
        $id = $_SESSION[self::page]['id'];
        $info = query(self::table, "id = '$id'");

        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑的权限';
        } elseif (empty($id)) {
            $json['warn'] = '未找到报酬清单ID';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '劳动报酬清单不是草稿状态，不能编辑';
        } else {
            $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x            = 0;
            $log          = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $detail = query(self::table_detail, " idCard = '".$cell['身份证号']."' and orderId = '$id'");
                    $labor = query('labor', "idCard = '".$cell['身份证号']."'");
                    if (!empty($detail['id'])) {
                        $log .= "第【{$i}】行：已存在此人员<br>";
                    } elseif (empty($labor['id'])) {
                        $log .= "第【{$i}】行：未在劳务名册中找到此人员<br>";
                    } else {
                        $field = [
                            "id" => self::getId(),
                            'orderId' => $id,
                            'laborId' => $labor['id'],
                            'name' => $cell['姓名'],
                            'idCard' => $cell['身份证号'],
                            'tel' => $cell['手机号码'],
                            'salaryDay' => $cell['出勤天数'],
                            'workDay' => $cell['受薪天数'],
                            'baseMoney' => $cell['基本工资'],
                            'jobMoney' => $cell['岗位工资'],
                            'telFee' => $cell['通讯补贴'],
                            'trafficFee' => $cell['交通补贴'],
                            'performance'=>$cell['绩效工资'],
                            'workAgeFee' => $cell['工龄工资'],
                            'educationFee' => $cell['学历津贴'],
                            'jobTitleFee' => $cell['学历津贴'],
                            'temperatureFee' => $cell['职称津贴'],
                            'overtimeFee' => $cell['加班补贴'],
                            'otherFee' => $cell['其他补贴'],
                            'leaveMoney' => $cell['病事假扣款'],
                            'lateMoney' => $cell['迟到早退'],
                            'otherDecMoney' => $cell['其他扣款'],
                            'money' => $cell['应发工资'],
                            'text' => $cell['备注'],
                        ];
                        $annotation = [
                            'name' => '姓名',
                            'tel' => '手机号',
                            'idCard' => '身份证号',
                        ];
                        $rules = [
                            'name' => 'required',
                            'tel' => 'required|tel',
                            'idCard' => 'required|id_card',
                        ];
                        // 校验是否符合规则
                        $vt = new \verify();
                        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                        if ($result === false) {
                            $log .= "第【{$i}】行：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                            continue;
                        } else {
                            $warn = insert(["table" => self::table_detail, "field" => $field]);
                            if (in_array($warn, ["新增成功", "更新成功"])) {
                                $x++;
                                $log .= "第【{$i}】行：导入成功<br>";
                            } else {
                                $log .= "第【{$i}】行：导入失败：编辑失败<br>" . $warn;
                            }
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$log,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $log;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'姓名',
                    'aliasName'=>'姓名',
                ],
                [
                    'columnName'=>'月份',
                    'aliasName'=>'月份',
                ],
                [
                    'columnName'=>'身份证号',
                    'aliasName'=>'身份证号',
                ],
                [
                    'columnName'=>'手机号码',
                    'aliasName'=>'手机号码',
                ],
                [
                    'columnName'=>'出勤天数',
                    'aliasName'=>'出勤天数',
                ],
                [
                    'columnName'=>'受薪天数',
                    'aliasName'=>'受薪天数',
                ],
                [
                    'columnName'=>'基本工资',
                    'aliasName'=>'基本工资',
                ],
                [
                    'columnName'=>'岗位工资',
                    'aliasName'=>'岗位工资',
                ],
                [
                    'columnName'=>'通讯补贴',
                    'aliasName'=>'通讯补贴',
                ],
                [
                    'columnName'=>'交通补贴',
                    'aliasName'=>'交通补贴',
                ],
                [
                    'columnName'=>'绩效工资',
                    'aliasName'=>'绩效工资',
                ],
                [
                    'columnName'=>'工龄工资',
                    'aliasName'=>'工龄工资',
                ],
                [
                    'columnName'=>'学历津贴',
                    'aliasName'=>'学历津贴',
                ],
                [
                    'columnName'=>'职称津贴',
                    'aliasName'=>'职称津贴',
                ],
                [
                    'columnName'=>'高温补贴',
                    'aliasName'=>'高温补贴',
                ],
                [
                    'columnName'=>'加班补贴',
                    'aliasName'=>'加班补贴',
                ],
                [
                    'columnName'=>'其他补贴',
                    'aliasName'=>'其他补贴',
                ],
                [
                    'columnName'=>'病事假扣款',
                    'aliasName'=>'病事假扣款',
                ],
                [
                    'columnName'=>'迟到早退',
                    'aliasName'=>'迟到早退',
                ],
                [
                    'columnName'=>'其他扣款',
                    'aliasName'=>'其他扣款',
                ],
                [
                    'columnName'=>'应发工资',
                    'aliasName'=>'应发工资',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ]
            ]
        };
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $id = $_SESSION[self::page]['id'];

        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有劳务派遣协议的编辑权限';
        } elseif (empty($id)) {
            $_SESSION['warn'] = '未找到派遣协议ID';
        } else {
            $info = query(self::table, "id = '$id'");

            $tr    = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table_detail,
                    "where" => "id in ('".implode("','", $checkedId)."') order by list asc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            if (is_array($result)) {
                foreach ($result as $k=>$array) {
                    $column = [];
                    foreach ($tempFieldAll as $templateField){
                        if ($templateField['display']){
                            $column[] = match ($templateField['columnName']){
                                '姓名'=>$array['name'],
                                '月份'=>$info['month'],
                                '身份证号'=>$array['idCard'],
                                '手机号码'=>$array['tel'],
                                '出勤天数'=>$array['workDay'],
                                '受薪天数'=>$array['salaryDay'],
                                '基本工资'=>$array['baseMoney'],
                                '岗位工资'=>$array['jobMoney'],
                                '通讯补贴'=>$array['telFee'],
                                '交通补贴'=>$array['trafficFee'],
                                '绩效工资'=>$array['performance'],
                                '工龄工资'=>$array['workAgeFee'],
                                '学历津贴'=>$array['educationFee'],
                                '职称津贴'=>$array['jobTitleFee'],
                                '高温补贴'=>$array['temperatureFee'],
                                '加班补贴'=>$array['overtimeFee'],
                                '其他补贴'=>$array['otherFee'],
                                '病事假扣款'=>$array['leaveMoney'],
                                '迟到早退'=>$array['lateMoney'],
                                '其他扣款'=>$array['otherDecMoney'],
                                '应发工资'=>$array['money'],
                                '备注'=>$array['text'],
                                default=>'',
                            };
                        }
                    }
                    $tr[] = $column;
                }
            }
            $text = $this->control['name'] . "导出了{$info['month']}劳动报酬清单";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $tr, "{$info['month']}劳动报酬清单.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'delMx':
                $act = 'del';
                $msg = '删除报酬清单' . self::title;
                $title = self::page . 'DetailDelete';
                $function = 'deleteMx';
                $form = self::page . 'OperateForm, recordForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = "不是草稿状态，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::table_detail, "where" => " orderId = '$id' "));
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    $all = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                    foreach ($all['array'] as $val) {
                        fileDelete($val['src']);
                        delete(array("table" => 'file', "where" => " id = '$val[id]' "));
                    }
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    public function deleteMx()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table . '_detail', " id = '$id' ");
                $parent = query(self::table, " id = '$info[orderId]' ");
                if ($parent['state'] != '草稿') {
                    $warn = "不是草稿状态，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table . '_detail', "where" => " id = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了派遣清单，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . ($parent['id'] ?? '');
        }
        return json_encode($json, 320);
    }
}

